#include "bang_shopkeeper_cache.h"

#include "base/logging.h"
#include "base/config_reader.h"
#include "database/scoped_connection.h"
#include "database/simple_db_pool.h"

#include <string>

namespace imserver {

BangShopKeeperCache::BangShopKeeperCache() : db_conn_pool_(NULL) {
  ConfigReader config("../conf/message_exchange_service.conf");

  db_conn_pool_ = new base::SimpleConnectionPool(config.Get("shop_db", "name").c_str(),
                      config.Get("shop_db", "server_list").c_str(),
                      config.Get("shop_db", "user").c_str(),
                      config.Get("shop_db", "password").c_str());
}

bool BangShopKeeperCache::Contains(int64_t uid) const {
  boost::shared_lock<boost::shared_mutex> rlock(mutex_);

  std::set<int64_t>::const_iterator it = shopkeepers_.find(uid);
  LOG_DEBUG("uid " << uid << " Contains=" << (it != shopkeepers_.end()));
  return it != shopkeepers_.end();
}

int BangShopKeeperCache::Reload() {
  if (db_conn_pool_ == NULL) {
    LOG_ERROR("BangShopKeeperCache::Reload failed on NULL database-pool.");
    return -1;
  }

  mysqlpp::ScopedConnection db(*db_conn_pool_);
  if (!db) {
    LOG_ERROR("BangShopKeeperCache::Reload failed to get a connection from database-pool.");
    return -1;
  }

  std::set<int64_t> shopkeepers;

  mysqlpp::Query query(db->query());
  query << "SELECT qid FROM shop_base";

  try {
    mysqlpp::UseQueryResult ret = query.use();
    if (ret) {
      while(mysqlpp::Row row = ret.fetch_row()) {
        shopkeepers.insert((int64_t)row["qid"]);
        LOG_DEBUG("load shop id " << (int64_t)row["qid"]);
      }
    }
  } catch (mysqlpp::Exception& e) {
    LOG_ERROR("BangShopKeeperCache::Reload " << query.str() << " EXEC ERROR.(" << e.what() << ")");
    return -2;
  }

  LOG_ERROR("BangShopKeeperCache::Reload OK, size=" << shopkeepers.size());
  shopkeepers.insert(127646892);
  {
    boost::unique_lock<boost::shared_mutex> wlock(mutex_);
    shopkeepers_.swap(shopkeepers);
  }
  return 0;
}

}

